<template>
	<div>
		<h3>演示watch computed以及父子组件传值的用法</h3>
		<pre>
			watch和watchEffect的区别:
			1.watch需要传入侦听数据源，watchEffect自动搜集数据源
			2.watch侦听状态前后的变化，watchEffect没有
			3.watch属性改变的时候执行，watchEffect先执行一次属性改变时再执行
		</pre>
		state.name: {{state.name}} <br>
		state.doubleCount: {{state.doubleCount}} <br>
		userName: {{userName}} <br>
		<el-button type="primary" @click="chaneName">点击修改state.name和userName</el-button>
		<hr />
		<Child :userInfo="state" :userName="userName" @handleChange="handleChange"></Child>
	</div>
</template>

<script>
	import {ref, reactive, computed, watch, watchEffect} from 'vue'
	import Child from './subComponent.vue'
	export default {
		components:{Child},
		setup(){
			let userName = ref('小明')
			const state = reactive({
				name: '张骞枫',
				count: 2,
				// 使用计算属性
				doubleCount: computed(() => state.count * 2),
			})
			
			// 监听ref声明的变量第一个参数直接使用
			/* watch(userName, (newValue, oldValue) => {
				console.log('userName change：', newValue, oldValue)
			})
			// 监听reactive声明的变量第一个参数使用函数返回值的形式
			watch(()=>state.name, (newValue, oldValue) => {
				console.log('state.name change：', newValue, oldValue)
			}) */
			// 监听多个变量以数组的形式入参
			watch([userName, ()=>state.name], (newValue, oldValue) => {
				console.log('state.name change：', newValue, oldValue)
			})
			// 使用watchEffect监听
			watchEffect(()=>{
				console.log('通过watchEffect监听数据-----', userName.value)
			})

			const chaneName = () => {
				state.name = '张骞枫1234'
				userName.value = '张三'
			}
			const handleChange = (val) => {
				state.name = val
			}
			
			return {state, userName, handleChange, chaneName}
		}
	}
</script>

<style>
</style>
